#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
进度管理器 - 支持断点续传
"""

import os
import json
import logging
from datetime import datetime
from typing import Optional, Dict, Any


class ProgressManager:
    """进度管理器"""
    
    def __init__(self, progress_dir: str, session_name: str = "export"):
        self.progress_dir = progress_dir
        self.session_name = session_name
        self.progress_file = os.path.join(progress_dir, f"{session_name}_progress.json")
        self.error_file = os.path.join(progress_dir, f"{session_name}_errors.jsonl")
        self.logger = logging.getLogger(__name__)
        
        # 确保进度目录存在
        os.makedirs(progress_dir, exist_ok=True)
        
        # 进度数据
        self.progress_data = {
            'last_processed_id': None,
            'processed_count': 0,
            'basic_facility_rows': 0,
            'facility_group_rows': 0,
            'error_count': 0,
            'start_time': None,
            'last_update_time': None,
            'session_name': session_name
        }
    
    def load_progress(self) -> bool:
        """加载进度文件"""
        if not os.path.exists(self.progress_file):
            self.logger.info("未找到进度文件，将从头开始")
            return False
        
        try:
            with open(self.progress_file, 'r', encoding='utf-8') as f:
                self.progress_data = json.load(f)
            
            self.logger.info("=" * 60)
            self.logger.info("找到上次的进度记录：")
            self.logger.info(f"  上次处理到的酒店ID: {self.progress_data.get('last_processed_id')}")
            self.logger.info(f"  已处理酒店数: {self.progress_data.get('processed_count')}")
            self.logger.info(f"  基本设施行数: {self.progress_data.get('basic_facility_rows')}")
            self.logger.info(f"  设施集合行数: {self.progress_data.get('facility_group_rows')}")
            self.logger.info(f"  错误数: {self.progress_data.get('error_count')}")
            self.logger.info(f"  上次更新时间: {self.progress_data.get('last_update_time')}")
            self.logger.info("=" * 60)
            
            return True
        except Exception as e:
            self.logger.error(f"加载进度文件失败: {str(e)}")
            return False
    
    def save_progress(self, 
                     last_processed_id: str,
                     processed_count: int,
                     basic_facility_rows: int,
                     facility_group_rows: int,
                     error_count: int):
        """保存进度"""
        try:
            self.progress_data.update({
                'last_processed_id': last_processed_id,
                'processed_count': processed_count,
                'basic_facility_rows': basic_facility_rows,
                'facility_group_rows': facility_group_rows,
                'error_count': error_count,
                'last_update_time': datetime.now().strftime('%Y-%m-%d %H:%M:%S')
            })
            
            # 如果是第一次保存，记录开始时间
            if not self.progress_data.get('start_time'):
                self.progress_data['start_time'] = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
            
            with open(self.progress_file, 'w', encoding='utf-8') as f:
                json.dump(self.progress_data, f, ensure_ascii=False, indent=2)
            
            self.logger.debug(f"进度已保存: 处理到酒店 {last_processed_id}")
        except Exception as e:
            self.logger.error(f"保存进度失败: {str(e)}")
    
    def log_error(self, hotel_id: str, error_type: str, error_message: str):
        """记录错误"""
        try:
            error_record = {
                'hotel_id': hotel_id,
                'error_type': error_type,
                'error_message': error_message,
                'timestamp': datetime.now().strftime('%Y-%m-%d %H:%M:%S')
            }
            
            with open(self.error_file, 'a', encoding='utf-8') as f:
                f.write(json.dumps(error_record, ensure_ascii=False) + '\n')
        except Exception as e:
            self.logger.error(f"记录错误失败: {str(e)}")
    
    def get_last_processed_id(self) -> Optional[str]:
        """获取上次处理的最后一个酒店ID"""
        return self.progress_data.get('last_processed_id')
    
    def get_processed_count(self) -> int:
        """获取已处理数量"""
        return self.progress_data.get('processed_count', 0)
    
    def clear_progress(self):
        """清除进度（重新开始）"""
        try:
            if os.path.exists(self.progress_file):
                os.remove(self.progress_file)
                self.logger.info("进度文件已清除")
            
            # 重置进度数据
            self.progress_data = {
                'last_processed_id': None,
                'processed_count': 0,
                'basic_facility_rows': 0,
                'facility_group_rows': 0,
                'error_count': 0,
                'start_time': None,
                'last_update_time': None,
                'session_name': self.session_name
            }
        except Exception as e:
            self.logger.error(f"清除进度失败: {str(e)}")
    
    def get_error_count(self) -> int:
        """获取错误总数"""
        if not os.path.exists(self.error_file):
            return 0
        
        try:
            with open(self.error_file, 'r', encoding='utf-8') as f:
                return sum(1 for _ in f)
        except:
            return 0

